package crawler.web.engine;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import library.database.mongo.MongoDB;
import library.office.ExcelWriter;

import org.junit.Test;

import com.mongodb.MongoException;

import crawler.web.beans.CrawlPageContext;

/**
 * @author waynechen May 7, 2012 7:24:12 PM
 */
public class ExportContext2Excel {
	@Test
	public void export() throws MongoException, FileNotFoundException, IOException, IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		MongoDB db = MongoDB.getInstance("192.168.17.36", 27017, "crawler");
		Iterator<CrawlPageContext> it = db.getIterator("context1", CrawlPageContext.class);
		ExcelWriter writer = new ExcelWriter("/home/waynechen/Desktop/data.xls");
		writer.openExcel();

		//設置头信息
		PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(CrawlPageContext.class).getPropertyDescriptors();
		List<String> list = new ArrayList<String>(propertyDescriptors.length);
		for (PropertyDescriptor p : propertyDescriptors) {
			list.add(p.getName());
		}
		writer.writeRow(list.toArray());

		int count = 0;
		//遍历数据库, 写入excel
		while (it.hasNext()) {
			list.clear();
			CrawlPageContext context = it.next();
			for (PropertyDescriptor p : propertyDescriptors) {
				if (p.getName().equals("tagData"))
					list.add("");
				else
					list.add(p.getReadMethod().invoke(context) + "");
			}
			writer.writeRow(list.toArray());
			if (count++ >= 1000) {
				writer.save();
				count = 0;
			}
		}

		//保存
		writer.save();
	}
}
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//